<?php

/**
 * This file is part of Webman AI.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 */

namespace plugin\ai\api;

use plugin\ai\app\event\data\HandlerData;
use plugin\ai\app\service\Common;
use RuntimeException;
use Webman\Event\Event;

class Base
{
    protected static function call($method, $data, $options)
    {
        if (empty($data['model'])) {
            throw new RuntimeException('缺少model参数');
        }
        $model = $data['model'];
        if (!$modelInfo = Common::getModelInfo($model)) {
            throw new RuntimeException("模型 $model 不存在或已禁用");
        }
        $handler = $modelInfo->handler;
        $handlerData = new HandlerData($data, $options, $handler);
        Event::dispatch('ai.model.handler.dispatch', $handlerData);
        $settings = [];
        foreach ($modelInfo->settings as $key => $item) {
            $settings[$key] = $item['value'] ?? '';
        }
        call_user_func([new $handlerData->handler($settings), $method], $handlerData->data, $handlerData->options);
    }

}